#!/bin/bash

. /etc/default/acpi-support
. /usr/share/acpi-support/power-funcs

function laptop_mode_enable {
    $LAPTOP_MODE start
    
    for x in /sys/bus/ide/devices/*/block; do 
	drive=$(basename $(readlink $x));
	$HDPARM -S 12 /dev/$drive 2>/dev/null
	$HDPARM -B 1 /dev/$drive 2>/dev/null
    done
    
    for x in /sys/bus/scsi/devices/*/block; do 
	drive=$(basename $(readlink $x));
	$HDPARM -S 12 /dev/$drive 2>/dev/null
	$HDPARM -B 1 /dev/$drive 2>/dev/null
    done
}

function laptop_mode_disable {
    for x in /sys/bus/ide/devices/*/block; do 
	drive=$(basename $(readlink $x));
	$HDPARM -S 0 /dev/$drive 2>/dev/null
	$HDPARM -B 255 /dev/$drive 2>/dev/null
    done
    for x in /sys/bus/scsi/devices/*/block; do 
	drive=$(basename $(readlink $x));
	$HDPARM -S 0 /dev/$drive 2>/dev/null
	$HDPARM -B 255 /dev/$drive 2>/dev/null
    done
    $LAPTOP_MODE stop
}

getState;

checkStateChanged;

shopt -s nullglob

for x in /proc/acpi/ac_adapter/*; do
    grep -q off-line $x/state

    if [ $? = 0 ] && [ x$1 != xstop ]; then	
	for SCRIPT in /etc/acpi/battery.d/*.sh; do
	    . $SCRIPT
	done
	if [ x$ENABLE_LAPTOP_MODE = xtrue ]; then
	    (sleep 5 && laptop_mode_enable)&
	fi
    else
	for SCRIPT in /etc/acpi/ac.d/*.sh; do
	    . $SCRIPT
	done
	if [ x$ENABLE_LAPTOP_MODE = xtrue ]; then
	    (sleep 5 && laptop_mode_disable)&
	fi
    fi
done